package com.baidu.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baidu.constant.MessageConstant;
import com.baidu.entity.Result;
import com.baidu.pojo.OrderSetting;
import com.baidu.service.OrderSettingService;
import com.baidu.utils.POIUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

	@Reference
	private OrderSettingService orderSettingService;

	/**
	 * Excel文件上传，并解析文件内容保存到数据库。
	 *
	 * 要明白：进数据库的不是文件，而是该文件转换成的java对象。
	 * @param excelFile
	 * @return
	 */

	@RequestMapping("/upload")
	public Result upload(@RequestParam("excelFile") MultipartFile excelFile ) throws IOException {

		try {
			List<String[]> excel = POIUtils.readExcel(excelFile);
			if (excel != null && excel.size() > 0) {
				ArrayList<OrderSetting> orderList = new ArrayList<>();
				OrderSetting orderSetting = null;
				for (String[] cell : excel) {//该数组表示单元格--

					orderSetting = new OrderSetting(new Date(cell[0]), Integer.valueOf(cell[1]));//解析文件集合封装为预约设置对象

					orderList.add(orderSetting);

				}

				orderSettingService.addOrder(orderList);
			}
			return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);


		} catch (IOException e) {

			return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);

		}


	}


	@RequestMapping("/getOdersettingByMonth")
	public Result getOdersettingByMonth(String date){ //通过传递过来的 参数 获得对应月份预约设置。yyyy-MM
			//日期格式，最好用String来接受，自己用Simpldateformart来转换。
		try {
			List<Map> list= orderSettingService.findOdersettingByMonth(date);
			return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
		} catch (Exception e) {
			return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
		}


	}

	@PreAuthorize("hasAuthority('ORDERSETTING')")
	@RequestMapping("/updateOrderNumber")
	public Result updateOrderNumber( @RequestBody OrderSetting orderSetting){

		try {
			orderSettingService.updateOrderNumber(orderSetting);
			return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
		} catch (Exception e) {
			return new Result(false, MessageConstant.ORDERSETTING_FAIL);
		}

	}


}
